<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="订单编号" prop="ordersNo">
        <el-input
          v-model="queryParams.ordersNo"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择订单状态"
          clearable
          size="small"
        >
          <el-option label="退单中" value="50" />
          <el-option label="已退单" value="60" />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="店铺接单状态" prop="distShopStatus" label-width="100px">-->
      <!--        <el-select v-model="queryParams.distShopStatus" placeholder="请选择店铺接单状态" clearable-->
      <!--                   size="small">-->
      <!--          <el-option label="待店铺接单" value="10"/>-->
      <!--          <el-option label="店铺接单" value="20"/>-->
      <!--          <el-option label="店铺拒绝" value="30"/>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:orders:remove']"
          >删除
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="refundOrdersList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="订单编号"
        align="center"
        prop="ordersNo"
        width="180"
      />
      <el-table-column label="退货方式" align="center" prop="returnType">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.returnType == '1'"
            >退款</el-tag
          >
          <el-tag type="warning" v-if="scope.row.returnType == '2'"
            >退货退款</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="申请时间"
        align="center"
        prop="createTime"
        width="180"
      />
      <el-table-column
        label="申请原因"
        align="center"
        prop="reason"
        width="180"
      />
      <el-table-column label="申请退款金额" align="center" prop="payment" />
      <el-table-column label="退款方式" align="center" prop="paymentType">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.paymentType == '1'"
            >微信支付</el-tag
          >
          <el-tag type="warning" v-if="scope.row.paymentType == '2'"
            >支付宝</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status == '3'">退单中</el-tag>
          <el-tag type="success" v-if="scope.row.status == '1'">已退单</el-tag>
          <el-tag type="warning" v-if="scope.row.status == '4'">已关闭</el-tag>
          <el-tag type="warning" v-if="scope.row.status == '0'">已取消</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="申请描述"
        align="center"
        prop="description"
        width="180"
      />
      <el-table-column label="商品摄图" align="center" prop="photo">
        <template slot-scope="scope" v-if="scope.row.photo != null">
          <el-image
            :preview-src-list="scope.row.photo.split(',')"
            style="width: 30px; height: 30px"
            shape="square"
            :src="image"
            :key="image"
            v-for="image in scope.row.photo.split(',')"
          ></el-image>
        </template>
      </el-table-column>
      <!--      <el-table-column label="自取状态" align="center" prop="selfStatus">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-tag type="warning" v-if="scope.row.selfStatus == '10'">待自取</el-tag>-->
      <!--          <el-tag type="success" v-if="scope.row.selfStatus == '20'">已取货</el-tag>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column
        label="手机号码"
        align="center"
        prop="phonenumber"
        width="180"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:orders:edit']"
            >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleRefund(scope.row)"
            v-hasPermi="['system:orders:edit']"
            >退款
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:orders:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单列对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :before-close="cancel"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row style="display: flex; justify-content: space-between">
          <el-form-item label="订单编号">
            <span>{{ "#" + form.ordersNo }}</span>
          </el-form-item>
          <el-form-item>
            <span
              v-if="form.payStatus == '10'"
              v-text="
                form.payOutTime <= currentTimeNow
                  ? '未支付(超时时间:' + parseTime(form.payOutTime) + ')'
                  : '未支付(已超时)'
              "
            ></span>
            <span v-if="form.payStatus == '20'"
              >已支付(支付时间:{{ parseTime(form.payTime) }})</span
            >
          </el-form-item>
        </el-row>

        <el-row style="display: flex; justify-content: space-between">
          <el-form-item label="配送方式">
            <span style="color: red" v-if="form.distType == '10'"
              >配送(预计配送时间 {{ form.distTime }})</span
            >
            <span style="color: red" v-if="form.distType == '20'">自提</span>
          </el-form-item>
          <el-form-item label="商品总价">
            <span>{{ form.totalPrice + "元" }}</span>
          </el-form-item>
          <el-form-item label="配送费用">
            <span>{{ form.distPrice + "元" }}</span>
          </el-form-item>
          <el-form-item label="合计支付">
            <span>{{ form.payPrice + "元" }}</span>
          </el-form-item>
          <el-form-item label="退款金额">
            <span>{{ form.payment + "元" }}</span>
          </el-form-item>
        </el-row>
        <el-collapse v-model="activeNames" @change="handleChange">
          <el-collapse-item title="订购商品详情" name="orderGoods">
            <el-table :data="orderGoodsList" style="width: 100%" border>
              <el-table-column prop="goodsName" label="商品名称" />
              <el-table-column prop="goodsImg" label="商品图">
                <template slot-scope="{ row }">
                  <el-image
                    class="classify-image"
                    :src="row.goodsImg"
                    :preview-src-list="[row.goodsImg]"
                    style="width: 100px; height: 100px"
                    fit="contain"
                    lazy
                  >
                    <div slot="error">
                      <i class="el-icon-document" />
                    </div>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="goodsPrice" label="商品价格" />
              <el-table-column prop="goodsNum" label="订购数量" />
            </el-table>
          </el-collapse-item>
          <el-collapse-item
            title="订单地址详情"
            name="orderAddress"
            v-if="form.distType == '10'"
          >
            <div style="display: flex; flex-wrap: wrap">
              <div style="width: 50%">
                收货人姓名：{{ orderAddressInfo.addressName }}
              </div>
              <div style="width: 50%">
                手机号：{{ orderAddressInfo.addressPhone }}
              </div>
              <div style="width: 50%">
                收货地址：{{ orderAddressInfo.addressInfo }}
              </div>
              <div style="width: 50%">
                门牌号：{{ orderAddressInfo.addressHouse }}
              </div>
              <div
                style="width: 50%"
                v-text="orderAddressInfo.sex == '10' ? '性别：男' : '性别：女'"
              ></div>
            </div>
          </el-collapse-item>
          <el-collapse-item
            title="配送点详情"
            name="orderPoint"
            v-if="form.distType == '20'"
          >
            <div style="display: flex; flex-wrap: wrap">
              <div style="width: 50%">
                分拣区域：{{ orderPointInfo.sortArea }}
              </div>
              <div style="width: 50%">
                配送点编号：{{ orderPointInfo.sortAreaNum }}
              </div>
            </div>
            <div style="width: 50%">名称:{{ orderPointInfo.pointName }}</div>
            <div style="width: 50%">自提点id:{{ orderPointInfo.pointId }}</div>
            <div style="width: 50%">用户Id:{{ orderPointInfo.courierId }}</div>
            <div style="width: 50%">
              自提点电话:{{ orderPointInfo.pointPhone }}
            </div>
            <div style="width: 50%">地址:{{ orderPointInfo.address }}</div>
            <div style="width: 50%">分拣区域:{{ orderPointInfo.sortArea }}</div>
            <web-map
              :isDistPoint="true"
              ref="webMap"
              :lng.sync="initLng"
              :lat.sync="initLat"
              :address.sync="orderPointInfo.address"
              scope.sync="1"
            ></web-map>
          </el-collapse-item>
          <el-collapse-item
            :title="riderTitle"
            name="orderRide"
            :disabled="riderOne"
            v-if="form.distType == '10'"
          >
            <div class="MainClass">
              <div class="MainChild">
                <img
                  style="width: 50px; height: 50px"
                  src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
                  alt=""
                />
                <div class="subClass">姓名: {{ orderRiderInfo.nickName }}</div>
                <div class="subClass">联系方式: {{ orderRiderInfo.phone }}</div>
              </div>
              <div class="MainChild">
                <!--配送状态 10=等待配送员接单 20=等待配送员取货 30=配送中 40=已送达-->
                <div class="subClass" v-if="form.distStatus == '10'">
                  当前状态： 等待配送员接单
                </div>
                <div class="subClass">接单时间： {{ form.distTime10 }}</div>
                <div class="subClass">取货时间： {{ form.distTime20 }}</div>
                <div class="subClass">送达时间： {{ form.distTime30 }}</div>
              </div>
            </div>
          </el-collapse-item>
          <el-collapse-item
            :title="自提详情"
            name="orderRideZiTi"
            v-if="form.distType == '20'"
          >
            <div style="display: flex; flex-wrap: wrap">
              <div style="width: 50%" v-if="form.selfStatus == '10'">
                自提状态：待自提
              </div>
              <div style="width: 50%" v-if="form.selfStatus == '20'">
                自提状态：已自提
              </div>
              <div style="width: 50%">预计自提时间：{{ form.selfTime }}</div>
              <div style="width: 50%" v-if="form.selfStatus == '20'">
                实际自提时间：{{ form.pickTime }}
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
        <el-row v-if="formStatus == 1">
          <el-form-item label="接单状态" style="margin-top: 20px">
            <el-radio-group v-model="form.distShopStatus">
              <el-radio-button label="20">确认接单</el-radio-button>
              <el-radio-button label="30">订单拒绝</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="操作描述" prop="distShopDesc">
            <el-input
              type="textarea"
              v-model="form.distShopDesc"
              placeholder="请输入操作描述"
            />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="formStatus == 1"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  refundList,
  refund,
  delRefund,
  addOrders,
  updateOrders,
  exportOrders,
  ship,
} from "@/api/system/refundOrder";
import { getOrderGoodsList } from "@/api/system/orderGoods"; //根据订单编号 查询订单商品明细
import { getOrderAddressDetil } from "@/api/system/orderAddress"; //根据订单编号 查询订单商品明细
import WebMap from "@/components/WebMap"; // svg component
import { getOrderPointDetil } from "@/api/system/orderPoint";
import { getOrderRiderDetil } from "@/api/system/orderCourier";
import { getOrders } from "@/api/system/orders";

export default {
  name: "Orders",
  components: { WebMap },
  data() {
    return {
      //是否有配送员
      riderOne: false, //是否可展开详情
      //是否配送
      isSelfGet: false,
      riderTitle: "配送员详情",
      // 遮罩层
      loading: true,
      initLng: "116.397428",
      initLat: "39.90923",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 退单列表格数据
      refundOrdersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open1: false,
      //折叠面板
      activeNames: ["0"],
      //当前时间
      currentTimeNow: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ordersNo: undefined,
        payStatus: undefined,
        payTime: undefined,
        payOutTime: undefined,
        totalPrice: undefined,
        distType: undefined,
        distPrice: undefined,
        distTime: undefined,
        pickTime: undefined,
        payPrice: undefined,
        payType: undefined,
        userId: undefined,
        shopId: undefined,
        status: undefined,
        distShopStatus: undefined,
        distShopTime: undefined,
        distShopDesc: undefined,
        distStatus: undefined,
        distTime10: undefined,
        distTime20: undefined,
        distTime30: undefined,
        selfStatus: undefined,
        selfTime: undefined,
        shipStatus: undefined,
      },
      // 表单参数
      form: {},
      form2: {},
      formStatus: 0,
      //查询详情订单商品明细
      orderGoodsList: [],
      //订购地址详情
      orderAddressInfo: "",
      //配送点详情
      orderPointInfo: "",
      //配送员详情
      orderRiderInfo: "",
      // 表单校验
      rules: {
        ordersNo: [
          { required: true, message: "订单编号不能为空", trigger: "blur" },
        ],
        payStatus: [
          {
            required: true,
            message: "支付状态 10未支付20已支付不能为空",
            trigger: "blur",
          },
        ],
        payOutTime: [
          { required: true, message: "支付超时时间不能为空", trigger: "blur" },
        ],
        totalPrice: [
          { required: true, message: "商品总价不能为空", trigger: "blur" },
        ],
        distType: [
          {
            required: true,
            message: "配送方式 10=配送 20=自取不能为空",
            trigger: "blur",
          },
        ],
        distPrice: [
          { required: true, message: "配送费不能为空", trigger: "blur" },
        ],
        payPrice: [
          { required: true, message: "合计支付不能为空", trigger: "blur" },
        ],
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" },
        ],
        shopId: [
          { required: true, message: "店铺ID不能为空", trigger: "blur" },
        ],
        status: [
          {
            required: true,
            message: "状态 10=进行中,20=取消,30=已完成,40=已关闭不能为空",
            trigger: "blur",
          },
        ],
        distShopStatus: [
          {
            required: true,
            message:
              "店铺接单状态 10=待店铺接单 20=店铺接单 30=店铺拒绝不能为空",
            trigger: "blur",
          },
        ],
        distStatus: [
          {
            required: true,
            message:
              "配送状态 10=等待配送员接单 20=等待配送员取货 30=配送中 40=已送达不能为空",
            trigger: "blur",
          },
        ],
        selfStatus: [
          {
            required: true,
            message: "自取状态 10=待自取,20=已取货不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    //折叠面板
    handleChange(val) {
      if (val[1] != undefined) {
        if (val[1] == "orderGoods") {
          if (this.orderGoodsList.length == 0) {
            //根据订单编号 获取订单商品明细
            getOrderGoodsList(this.form.ordersId).then((response) => {
              this.orderGoodsList = response.data;
            });
          }
        } else if (val[1] == "orderAddress") {
          //获取订单地址详情
          if (this.orderAddressInfo == "") {
            getOrderAddressDetil(this.form.ordersId).then((response) => {
              this.orderAddressInfo = response.data;
            });
          }
        } else if (val[1] == "orderPoint") {
          //获取配送点详情
          if (this.orderPointInfo.ordersPointId == undefined) {
            getOrderPointDetil(this.form.ordersId).then((response) => {
              this.orderPointInfo = response.data;
            });
            let that = this;
            setTimeout(function () {
              that.$refs.webMap.init(
                String(that.orderPointInfo.lng),
                String(that.orderPointInfo.lat)
              );
              that.$refs.webMap.setRadius(1);
            }, 1000);
          }
        } else if (val[1] == "orderRide") {
          //获取配送员详情
          getOrderRiderDetil(this.form.ordersId).then((response) => {
            this.orderRiderInfo = response.data;
          });
        }
      }
    },
    /** 查询订单列列表 */
    getList() {
      this.loading = true;
      refundList(this.queryParams).then((response) => {
        this.refundOrdersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      //查询详情订单商品明细
      this.orderGoodsList = [];
      //订购地址详情
      this.orderAddressInfo = "";
      //配送点详情
      this.orderPointInfo = "";
      //配送员详情
      this.orderRiderInfo = "";
      this.reset();
    },
    cancel1() {
      this.open1 = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ordersId: undefined,
        ordersNo: undefined,
        payStatus: "0",
        payTime: undefined,
        payOutTime: undefined,
        totalPrice: undefined,
        distType: undefined,
        distPrice: undefined,
        distTime: undefined,
        pickTime: undefined,
        payPrice: undefined,
        payType: undefined,
        userId: undefined,
        shopId: undefined,
        delFlag: undefined,
        createTime: undefined,
        updateTime: undefined,
        remark: undefined,
        status: "0",
        distShopStatus: "0",
        distShopTime: undefined,
        distShopDesc: undefined,
        distStatus: "0",
        distTime10: undefined,
        distTime20: undefined,
        distTime30: undefined,
        selfStatus: "0",
        selfTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.ordersId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单列";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.activeNames = ["0"];
      this.currentTimeNow = new Date();
      const ordersId = row.ordersId || this.ids;
      getOrders(ordersId).then((response) => {
        this.form = response.data;
        if (this.form.distStatus == "10") {
          //未接单
          this.riderOne = true; //是否可展开详情
          this.riderTitle = "配送员详情(未接单)";
        }
        if (this.form.distType == "20") {
          //订单配送方式 10 配送 20 自提
          this.isSelfGet = true;
        }
        if (this.form.payStatus == "20" && this.form.distShopStatus == "10") {
          this.formStatus = 1;
        }
        this.open = true;
        this.title = "订单详情";
      });
    },
    /** 退款按钮操作 */
    handleRefund(row) {
      const ordersReturnId = row.ordersReturnId;
      const ordersNo = row.ordersNo;
      const payment = row.payment;
      this.$confirm(
        '是否确认退款,订单列编号为"' + ordersNo + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
          showInput: true,
          inputValue: payment,
          inputPlaceholder: "请输入退款金额",
        }
      )
        .then((data) => {
          if (data.value <= payment && data.value > 0) {
            return refund(ordersReturnId, data.value);
          } else {
            this.msgError("退款金额已超出范围");
            return Promise.reject();
          }
        })
        .then(() => {
          this.getList();
          this.msgSuccess("退款成功");
        })
        .catch(function () {
          console.log("7");
        });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.ordersId != undefined) {
            updateOrders(this.form).then((response) => {
              this.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrders(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ordersReturnIds = row.ordersReturnId || this.ids;
      this.$confirm(
        '是否确认删除订单列编号为"' + ordersReturnIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delRefund(ordersReturnIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有订单列数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportOrders(queryParams);
        })
        .then((response) => {
          this.download(response.data);
        })
        .catch(function () {});
    },
  },
};
</script>
<style scoped>
.MainClass {
  display: flex;
  flex-wrap: wrap;
  padding: 5px 40px;
}

.MainChild {
  display: flex;
  flex-direction: column;
  width: 50%;
}

.subClass {
  margin-top: 10px;
}
</style>
